import requests
import hashlib
import time
import random

# 你的有道翻译API Key和密钥
app_key = '6aa9d807529bdfad'
app_secret = 'xoDnEQ7AxtCbVOwcQPbVb7DBlUOapzQF'


def encrypt(signStr):
    hash_algorithm = hashlib.md5()
    hash_algorithm.update(signStr.encode('utf-8'))
    return hash_algorithm.hexdigest()


def translate(text, from_lang='AUTO', to_lang='AUTO'):
    url = 'https://openapi.youdao.com/api'
    salt = str(random.randint(1, 65536))
    curtime = str(int(time.time()))
    sign_str = app_key + truncate(text) + salt + curtime + app_secret
    sign = encrypt(sign_str)

    payload = {
        'q': text,
        'from': from_lang,
        'to': to_lang,
        'appKey': app_key,
        'salt': salt,
        'sign': sign,
        'signType': 'v3',
        'curtime': curtime,
    }

    response = requests.post(url, data=payload)
    result = response.json()

    if result['errorCode'] == '0':
        return result['translation'][0]
    else:
        raise Exception(f"Error: {result['errorCode']}")


def truncate(q):
    if q is None:
        return None
    size = len(q)
    return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]


# 示例翻译
text = "对象窗体高度"
translated_text = translate(text, from_lang='zh-CHS', to_lang='EN')
print(f"原文: {text}")
print(f"翻译: {translated_text}")
